package meteocal.gui.security;


import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.faces.component.UIComponent;
import javax.inject.Inject;
import meteocal.business.control.ForecastChecker;

/**
 *
 * @author luana
 */

@Named
@RequestScoped
public class LoginBean{
    private String username;
    private String password;
    
    @Inject 
    ForecastChecker fc; 
    
    private UIComponent component;

    public UIComponent getComponent() {
        return component;
    }

    public void setComponent(UIComponent component) {
        this.component = component;
    }
    public LoginBean() {
    }

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }

    public void setUsername(String username) {
        this.username = username;
    }
    
    public void setPassword(String password) {
        this.password = password;
    }
    
    
    public String login(){
        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
        
        try {
            
            request.login(this.username, this.password);
            fc.checkEvent();
            return "user/main-page";
        } 
        catch (ServletException e) {
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"Login Failed","Login Failed!"));
            return "index";
        }
    }
    
    
    public String logout (){
        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
        
        request.getSession().invalidate();
        return "/index?faces-redirect=true";
        
    }
    
}




